package demo;

import java.net.URI;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

public class ClientImpl implements ClientInterface {
	private static final Logger log = Logger.getLogger(ClientImpl.class
			.getName());
	private ServerInterface serverStub;

	public ClientImpl() {
		super();
		 init();
	}

	@Override
	public void connectWithMe(String name, URI uri) throws RemoteException {
		
		try {
			System.out.println("calling connectWithMe");
			Registry registry = LocateRegistry.getRegistry("localhost", 0);
			serverStub = (ServerInterface) registry.lookup(name);
			System.out.println("user reconnected");
		} catch (NotBoundException e) {
			e.printStackTrace();
		}

	}

	private void init() {
		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new SecurityManager());
		}
		try {
			UnicastRemoteObject.exportObject(this, 0);
			log.debug("client export himself from callback");
		} catch (RemoteException re) {
			log.debug("Error.client can't export himself from callback");
			re.printStackTrace();
		}
		initializeServer();

	}

	private void initializeServer() {
		

		try {
			Registry registry = LocateRegistry.getRegistry( 0);
			serverStub = (ServerInterface) registry.lookup("primary_server");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		try {
			Boolean result = serverStub.login("user1", this);
			System.out.println("use login in");
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ClientImpl client = new ClientImpl();
		client.run();
		JOptionPane.showMessageDialog(null, "client runing");
	}

}
